﻿<!--
 * @Description: Chart图表（只有一个Chart组件）
 -->

<template>
  <ECharts :options="chartOptions" />
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useSignalRStore } from "@/store/modules/signalr.store";
import { SignalrToken } from "@/enums/business/signalrToken.enum";
import { EnumDeviceTypeCommon } from "@/enums";
import deviceApi from "@/api/business/device.api";
import { formatDate } from "date-fns";

const props = defineProps<{
  stationNum: number;
  sensorLegends: string[];
}>();

const signalrStore = useSignalRStore();

// 图表配置
const chartOptions = ref({
  legend: {
    type: "scroll",
    bottom: 5,
  },
  tooltip: {
    trigger: "axis",
  },
  xAxis: {
    type: "time" as const,
  },
  yAxis: {
    name: "%RH",
    type: "value" as const,
  },
  series: [] as {
    id: number;
    name: string;
    type: "line";
    smooth: boolean;
    showSymbol: boolean;
    data: [Date, number][];
  }[],
});
// 图表最大显示时长
const chartDataMaxSecond = 5 * 60;

// 添加数据点的方法
function addDeviceValue(deviceId: number, value: number) {
  value = Math.round(value * 100) / 100;
  let now = new Date();
  now = new Date(formatDate(now, "yyyy-MM-dd HH:mm:ss"));
  const series = chartOptions.value.series.find((item) => item.id === deviceId);
  if (!series) return;

  // 添加新数据
  series.data.push([now, value]);

  // 删除时间在 chartDataMaxSecond 秒之前的数据
  series.data = series.data.filter((item) => {
    return now.getTime() - item[0].getTime() <= chartDataMaxSecond * 1000;
  });

  // 可选：更新图表（某些情况下需要）
  // chartInstance.setOption({ series }, true);
}

/**
 * 添加传感器数据
 * @param sensorCode
 * @param value
 */
function addSensorValue(sensorCode: string, value: number) {
  value = Math.round(value * 100) / 100;
  if (value == -9999) return;
  let now = new Date();
  now = new Date(formatDate(now, "yyyy-MM-dd HH:mm:ss"));
  const series = chartOptions.value.series.find((item) => item.name === sensorCode);
  if (!series) return;
  // 添加新数据
  series.data.push([now, value]);

  // 删除时间在 chartDataMaxSecond 秒之前的数据
  series.data = series.data.filter((item) => {
    return now.getTime() - item[0].getTime() <= chartDataMaxSecond * 1000;
  });

  // 可选：更新图表（某些情况下需要）
  // chartInstance.setOption({ series }, true);
}

// 订阅 SignalR 消息
onMounted(() => {
  deviceApi.getStationDevices(props.stationNum).then((res) => {
    // 查找当前 stationNum 下的 Generator 和 Standard 设备
    const generatorDevice = res.find((item) => item.deviceType === EnumDeviceTypeCommon.Generator);
    const standardDevice = res.find((item) => item.deviceType === EnumDeviceTypeCommon.Standard);

    // 清空现有系列
    chartOptions.value.series = [];

    // 添加 Generator 设备
    if (generatorDevice) {
      chartOptions.value.series.push({
        id: generatorDevice.id,
        name: generatorDevice.deviceName,
        type: "line",
        smooth: true,
        showSymbol: false,
        data: [],
      });
    }
    // 添加 Standard 设备
    if (standardDevice) {
      chartOptions.value.series.push({
        id: standardDevice.id,
        name: standardDevice.deviceName,
        type: "line",
        smooth: true,
        showSymbol: false,
        data: [],
      });
    }

    // 添加传感器曲线
    props.sensorLegends.forEach((code, index) => {
      chartOptions.value.series.push({
        id: 999 + index,
        name: code,
        type: "line",
        smooth: true,
        showSymbol: false,
        data: [],
      });
    });
  });

  signalrStore.subscribe(SignalrToken.ChartDeviceValue, addDeviceValue);
  signalrStore.subscribe(SignalrToken.SensorVal, addSensorValue);
});
</script>

<style scoped lang="scss"></style>
